package com.example.jnivxbuffer;

import android.graphics.Color;
import android.opengl.GLES30;
import android.os.Bundle;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import android.view.SurfaceView;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;

import com.example.jnivxbuffer.AppDisplay;
import android.opengl.GLES20;

public class MainActivity extends AppCompatActivity {
    static {
        System.loadLibrary("native-lib");
    }
    public native String stringFromJNI();

    private SurfaceView surfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Log.v("MainActivity", "JNI function return:" + stringFromJNI());

        surfaceView = findViewById(R.id.surface_view);
        AppDisplay display = new AppDisplay(surfaceView.getHolder().getSurface());

        // 添加SurfaceHolder的回调
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                // Surface创建成功，可以开始OpenGL渲染
                Log.d("MainActivity", "--------------surfaceCreated------------");
                //surfaceView.setBackgroundColor(Color.argb(255, 128, 0, 0));       // this color would cover opengl surface!
                display.initResources();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                // Surface大小改变  glViewport
                Log.d("MainActivity", "--------------surfaceChanged------------");
                Log.d("MainActivity", "surface width:" + width + " height:" + height);
                GLES30.glViewport(0,0, width, height);

                GLES30.glClearColor(0.0f, 0.5f, 0.0f, 1.0f);
                GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
                 display.swapBuffer();
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                // Surface被销毁，释放资源
                Log.d("MainActivity", "--------------surfaceDestroyed------------");
                display.releaseResources();
            }
        });

        Button exitButton = findViewById(R.id.btn_exit);
        exitButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                // 结束当前活动
                //finish();           // 从活动栈顶移除，但app还在后台运行
                finishAffinity();   // 结束当前活动及其所有父活动
            }
        });
    }
}